package cn.algorithms_4ed.base.dataStructure;

import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * #请替换掉这里的东东#
 * <p/>
 * User: erhu
 * Date: 13-6-11
 * Time: 下午10:26
 */
public class ResizingArrayStack<T> implements Iterable<T> {

    private T[] data = (T[]) new Object[1];
    private int size;


    public void push(T item) {
        if (size == data.length) {
            resize(size << 1);
        }
        data[size++] = item;
    }

    public T pop() {
        T item = data[--size];
        data[size] = null;

        if (size > 0 && size == data.length / 4) {
            resize(size >> 1);
        }
        return item;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    @Override
    public Iterator<T> iterator() {
        return new Iterator<T>() {
            private int i = size;

            @Override
            public boolean hasNext() {
                return i > 0;
            }

            @Override
            public T next() {
                if (hasNext()) {
                    return data[--i];
                } else {
                    throw new NoSuchElementException();
                }
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
    }

    private void resize(int max) {
        T[] tmp = (T[]) new Object[max];
        System.arraycopy(data, 0, tmp, 0, size);
        /*for (int i = 0; i < size; i++) {
            tmp[i] = data[i];
        }*/
        data = tmp;
    }
}
